package com.zhg.videorecord.helper;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.media.MediaMetadataRetriever;
import android.os.AsyncTask;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * desc:  todo
 * author: ZHG
 * date: 2020/3/17
 */
public class VideoCoverUtil {
    private static String mVideoPath;
    private static String mImagePath;



    /**
     * 获取本地视频的第一帧
     *
     * @param localPath
     * @return
     */
    public static Bitmap getLocalVideoBitmap(String localPath) {
        Bitmap bitmap = null;
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        try {
            retriever.setDataSource(localPath);
            bitmap = retriever.getFrameAtTime();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } finally {
            retriever.release();
        }
        return bitmap;
    }

    /**
     * 压缩图片
     */
    private static Bitmap compressImage(Bitmap image) {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        int options = 90;

        while (baos.toByteArray().length / 1024 > 100) {
            baos.reset();
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);
            options -= 10;
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);
        return bitmap;
    }
    public static String createFrameImage(String videoPath){
        mVideoPath=videoPath;
        new ImageTask().execute();
        return mImagePath;
    }

    /**
     * 获取到视频第一帧
     */
    static  class ImageTask extends AsyncTask<Void, Void, String> {

        private File videoImageFile;

        @Override
        protected String doInBackground(Void... voids) {

            videoImageFile = new File(mVideoPath.replace(".mp4",".jpeg"));
            MediaMetadataRetriever mmr = new MediaMetadataRetriever();
            mmr.setDataSource(mVideoPath);
            //String duration = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION); // 播放时长单位为毫秒
            //videoTime = (int) (Integer.parseInt(duration) * 0.001);
            //Bitmap bitmap = ImageUtils.compressImage(mmr.getFrameAtTime(), 50, 50);
            Bitmap bitmap = compressImage(mmr.getFrameAtTime());
            try {
                FileOutputStream out = new FileOutputStream(videoImageFile);
                bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
                out.flush();
                out.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }catch (Exception e){
                e.printStackTrace();
            }

            return videoImageFile.toString();
        }



        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
        }
    }
    /**
     * desc: 从预览数据中保存缩略图
     * author: ZHG
     * date: 2020/4/20
     */
    public static void convertNv21ToJpeg(final String path, final byte[] data, final int width, final int height) {
        new AsyncTask<Void, Void, String>() {
            @Override
            protected String doInBackground(Void... voids) {
                String jpegPath=path;
                if (!path.endsWith("jpeg")){
                    jpegPath = path.replace(".mp4",".jpeg");
                }
                File jpegFile = new File(jpegPath);
                FileOutputStream fos = null;
                if (!jpegFile.exists()) {
                    try {
                        jpegFile.createNewFile();
                        fos = new FileOutputStream(jpegFile);
                        //将NV21 data保存成YuvImage
                        YuvImage image = new YuvImage(data, ImageFormat.NV21, width, height, null);
                        //图像压缩 将NV21格式图片，以质量70压缩成Jpeg，并得到JPEG数据流
                        image.compressToJpeg(new Rect(0, 0, image.getWidth(), image.getHeight()), 70, fos);
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        if (fos != null) {
                            try {
                                fos.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
                return null;
            }
        }.execute();


    }

}
